package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.IotClientConfig;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备管理Service业务层处理
 *
 * @author xjl
 * @date 2025-10-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        String products = redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        List<ProductVo> productVo = JSONUtil.toList(products, ProductVo.class);
        return productVo;
    }

    @Override
    public void register(DeviceDto dto) {

        //判断设备名称是否重入
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getDeviceName, dto.getDeviceName());
        Device device1 = this.getOne(queryWrapper1);
        if (device1 != null) {
            throw new BaseException("设备名称重入");
        }
        //判断设备标识是否重入
        LambdaQueryWrapper<Device> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Device::getNodeId, dto.getNodeId());
        Device device2 = this.getOne(queryWrapper2);
        if (device2 != null) {
            throw new BaseException("设备标识重入");
        }
        //判断设同一个位置是否有同一种设备
        LambdaQueryWrapper<Device> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(Device::getProductName, dto.getProductName());
        queryWrapper3.eq(Device::getRemark, dto.getRemark());
        Device device3 = this.getOne(queryWrapper3);
        if (device3 != null) {
            throw new BaseException("同一个位置有重复设备");
        }
        //先注册IOT产品
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        //addDevice.setDeviceId();
        addDevice.setNodeId(dto.getNodeId());//设备标识码
        addDevice.setDeviceName(dto.getDeviceName());
        addDevice.setProductId(dto.getProductKey());
        AuthInfo authInfo = new AuthInfo();
        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        addDevice.setDescription(dto.getDeviceDescription());

        request.setBody(addDevice);
        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("IOT注册设备失败");
        }

        //在存入数据库
        Device device = new Device();
        String deviceId = response.getDeviceId();
        device.setIotId(deviceId);
        device.setSecret(secret);
        device.setBindingLocation(dto.getBindingLocation() + "");
        device.setLocationType(dto.getLocationType());
        device.setPhysicalLocationType(dto.getPhysicalLocationType());
        device.setDeviceName(dto.getDeviceName());
        device.setProductKey(dto.getProductKey());
        device.setProductName(dto.getProductName());
        device.setDeviceDescription(dto.getDeviceDescription());
        //device.setHaveEntranceGuard();
        device.setNodeId(response.getNodeId());
        device.setRemark(dto.getRemark());
        this.save(device);

    }

    @Override
    public DeviceDetailVo deviceDetail(String iotId) {
        //先查自己的表
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device device = this.getOne(queryWrapper);
        if (device == null) {
            throw new BaseException("参数有误");
        }
        /*DeviceDetailVo deviceDetailVo=new DeviceDetailVo();
        deviceDetailVo.setIotId(device.getIotId());
        deviceDetailVo.setDeviceName(device.getDeviceName());
        deviceDetailVo.setNodeId(device.getDeviceName());
        deviceDetailVo.setSecret(device.getSecret());
        deviceDetailVo.setProductKey(device.getProductKey());
        deviceDetailVo.setProductName(device.getProductName());
        deviceDetailVo.setLocationType(device.getLocationType());
        deviceDetailVo.setBindingLocation(Long.valueOf(device.getBindingLocation()));
        deviceDetailVo.setRemark(device.getRemark());
        //deviceDetailVo.setDeviceStatus();
        //deviceDetailVo.setActiveTime();*/

        //两种用一即可
        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //再查IOT
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("IOT查询失败");
        }
        String active = response.getActiveTime();
        LocalDateTime parse = LocalDateTimeUtil.parse(active, DatePattern.UTC_MS_PATTERN);
        // DateTimeZoneConverter是今天资料中提供的一个工具类
        LocalDateTime activeTime = DateTimeZoneConverter.utcToShanghai(parse);
        detailVo.setActiveTime(activeTime);
        detailVo.setDeviceStatus(response.getStatus());
        return detailVo;
    }

    @Override
    public List<DeviceDataVo> queryProduct(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("IOT查询失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        DeviceShadowData deviceShadowData = shadow.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();
        String eventTimeStr = reported.getEventTime();
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // DateTimeZoneConverter是今天资料中提供的一个工具类
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(parse);

        List<DeviceDataVo> deviceDataVos = new ArrayList<>();
        LinkedHashMap<String, Object> properties = (LinkedHashMap) reported.getProperties();
        for (String key : properties.keySet()) {
            DeviceDataVo deviceDataVo = new DeviceDataVo();
            deviceDataVo.setFunctionId(key);
            deviceDataVo.setEventTime(eventTime);
            deviceDataVo.setValue(properties.get(key));
            deviceDataVos.add(deviceDataVo);
        }
        return deviceDataVos;
    }

    @Override
    public void updateDevice(DeviceDto dto) {
        //检测名称是否相同
        LambdaQueryWrapper<Device> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getDeviceName,dto.getDeviceName());
        Device device1 = this.getOne(queryWrapper1);
        if (device1 !=null){
            throw new BaseException("名称相同");
        }

        //检测是不是同一位置同一款商品
        LambdaQueryWrapper<Device> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getProductKey,dto.getProductKey());
        queryWrapper.eq(Device::getRemark,dto.getRemark());
        queryWrapper.ne(dto.getId() != null, Device::getId, dto.getId());
        Device device = this.getOne(queryWrapper);
        if (device !=null){
            throw new BaseException("同一位置不能有同一款商品");
        }

        //先修改平台
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(dto.iotId);

        UpdateDevice updateDevice = new UpdateDevice();

        updateDevice.setDeviceName(dto.getDeviceName());
        updateDevice.setDescription(dto.getDeviceDescription());
        Map<String, Object> extensionInfo = new HashMap<>();
        extensionInfo.put("bindingLocation", dto.getBindingLocation());
        extensionInfo.put("locationType", dto.getLocationType());
        extensionInfo.put("nodeId", dto.getNodeId());
        extensionInfo.put("physicalLocationType", dto.getLocationType());
        extensionInfo.put("productKey", dto.getProductKey());
        extensionInfo.put("productName", dto.getProductName());
        extensionInfo.put("remark", dto.getRemark());
        updateDevice.setExtensionInfo(extensionInfo);

        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        updateDevice.setAuthInfo(authInfobody);
        request.setBody(updateDevice);
        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("修改失败");
        }

        //修改数据库
        LambdaUpdateWrapper<Device> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.eq(Device::getIotId,dto.iotId);
        updateWrapper.set(Device::getDeviceName,dto.getDeviceName());
        updateWrapper.set(Device::getRemark,dto.getRemark());
        this.update(updateWrapper);
    }

    @Override
    public void deleteDevice(String iotId) {
        //先删除数据库
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        this.remove(queryWrapper);
        //在删除云端
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode()!=204){
            throw new BaseException("删除失败");
        }
    }

    @Override
    public AjaxResult queryProductKey(String productKey) {
        ShowProductRequest request=new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode()!=200){
            throw new BaseException("IOT查询错误");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        return AjaxResult.success(serviceCapabilities);
    }


}
